package system.util;

import com.google.common.collect.Lists;
import system.model.vo.AuthorityTreeNodeVo;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 米泽鹏
 */
public class MenuTreeBuilder {

	private MenuTreeBuilder() {
		throw new AssertionError("不可实例化");
	}

	public static List<AuthorityTreeNodeVo> buildMenuTree(List<AuthorityTreeNodeVo> allNodes) {
		// 根节点
		List<AuthorityTreeNodeVo> root = Lists.newArrayList();
		allNodes.forEach(node -> {
			if (node.getParentId().equals(0L)) {
				root.add(node);
			}
		});
		root.forEach(node -> findMenuChildren(node, allNodes));
		// 对根节点排序
		List<AuthorityTreeNodeVo> sortedList = root.stream().sorted(Comparator.comparing(AuthorityTreeNodeVo::getSort)).collect(Collectors.toList());
		// 先清空，再添加
		root.clear();
		root.addAll(sortedList);
		return root;
	}

	/**
	 * 递归查找子节点
	 */
	private static AuthorityTreeNodeVo findMenuChildren(AuthorityTreeNodeVo treeNode, List<AuthorityTreeNodeVo> treeNodes) {
		for (AuthorityTreeNodeVo it : treeNodes) {
			if (treeNode.getId().equals(it.getParentId())) {
				treeNode.getChildren().add(findMenuChildren(it, treeNodes));
			}
		}
		// 对子节点排序
		List<AuthorityTreeNodeVo> childrenSorted = treeNode.getChildren().stream().sorted(Comparator.comparing(AuthorityTreeNodeVo::getSort)).collect(Collectors.toList());
		// 先清空，再添加
		treeNode.getChildren().clear();
		treeNode.getChildren().addAll(childrenSorted);
		return treeNode;
	}

}
